import Bullet from "./Bullet";
import Player from "./Player";
import AngleUtils from "./Trigon/AngleUtils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class TouchController extends cc.Component {
	@property(cc.Prefab)
	bulletPrefab: cc.Prefab | null = null;

	private _isTouch:boolean=false;
	private _target:cc.Vec3=cc.v3();

	onLoad() {
		
	}

	onEnable(){
		this.node.parent.on(
			cc.Node.EventType.TOUCH_START,
			this.onTouchStart,
			this
		);
		this.node.parent.on(
			cc.Node.EventType.TOUCH_MOVE,
			this.onTouchMove,
			this
		);
		this.node.parent.on(
			cc.Node.EventType.TOUCH_END,
			this.onTouchEnd,
			this
		);
		this.node.parent.on(
			cc.Node.EventType.TOUCH_CANCEL,
			this.onTouchEnd,
			this
		);
	}

	onDisable(){
		this.node.parent.off(
			cc.Node.EventType.TOUCH_START,
			this.onTouchStart,
			this
		);
		this.node.parent.off(
			cc.Node.EventType.TOUCH_MOVE,
			this.onTouchMove,
			this
		);
		this.node.parent.off(
			cc.Node.EventType.TOUCH_END,
			this.onTouchEnd,
			this
		);
		this.node.parent.off(
			cc.Node.EventType.TOUCH_CANCEL,
			this.onTouchEnd,
			this
		);
	}

	start() {}

	interval:number=0
	delay:number=4/60.0;	
	update (dt) {
		if(!this._isTouch){
			return;
		}
		if(this.interval>this.delay){
			this.fire(this._target);
			this.interval-=this.delay;
		}
		this.interval+=dt;
	}

	fire(target:cc.Vec3){
		if(Player.instance.bullet<=0){
			return;
		}
		let b = this.spawnBullet()
		b.position = this.node.position
		let bullet = b.getComponent(Bullet)
		let radian = AngleUtils.getAngle(this.node.position, target)
		b.angle = AngleUtils.radianToAngle(radian)
		bullet.Angle = radian
		Player.instance.bullet-=1;
	}

	onTouchStart(e: cc.Event.EventTouch) {
		this._isTouch=true
		this._target= this.node.parent.convertToNodeSpaceAR(cc.v3(e.getLocation()))
		//this.fire(this._target);
	}

	onTouchMove(e:cc.Event.EventTouch){
		this._target= this.node.parent.convertToNodeSpaceAR(cc.v3(e.getLocation()))
	}

	onTouchEnd(e: cc.Event.EventTouch){
		this._isTouch=false
	}

	spawnBullet() {
		if (this.bulletPrefab == null) {
			return;
		}
		let b = cc.instantiate(this.bulletPrefab);
		this.node.parent.addChild(b);
		return b;
	}
}
